// Global Variables - When possible pulling form Local Storage set via Options page.
var activeWindows = new Array();
var timeDelay = 10000;
if (localStorage["seconds"]) { timeDelay = (localStorage["seconds"]*1000);}
var tabReload = true;
var moveinterval = 0;
var chromeFocusLost = false;
var sessionIdleState = false;

if (localStorage["reload"]) { 
	if (localStorage["reload"] == 'true') {
		tabReload = true;
	} else {
		tabReload = false;
	}
}

var tabInactive = false;
if (localStorage["inactive"]) { 
	if (localStorage["inactive"] == 'true') {
		tabInactive = true;
	} else {
		tabInactive = false;
	}
}

var chromeFocusTick = false;
if (localStorage["browserfocus"]) {
	if (localStorage["browserfocus"] == 'true') {
		chromeFocusTick = true;
	} else {
		chromeFocusTick = false;
	}
}

function activeInWindow(windowId)
{
	for(i in activeWindows) {
		if(activeWindows[i] == windowId) {
			return true;
		}
	}
}

// Setup Initial Badge Text
var badgeColor = [139,137,137,137];
chrome.browserAction.setBadgeBackgroundColor({color: badgeColor});

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
	var windowId = tab.windowId
	if (activeInWindow(windowId)) {
		stop(windowId);
	} else {
		go(windowId);
	}
});

chrome.windows.onFocusChanged.addListener(function(windowId) {
	chromeFocusLost = (windowId == -1) ? true : false;
	//console.log(' Chrome Focus State: ' +chromeFocusLost);
});

chrome.idle.onStateChanged.addListener(function(state) {
	sessionIdleState = (state == "active") ? true : false;
	console.log(' Query State is: ' +sessionIdleState);
});

chrome.idle.queryState(15, function(state) {
	
	// 15 is the lowest allowable number of seconds for this call, if you try lower, Chrome complains
	//sessionIdleState = (state == "idle") ? true : false;
	
});

function badgeTabs(windowId, text) {
	chrome.tabs.getAllInWindow(windowId, function(tabs) {
		for(i in tabs) {
			switch (text)
			{
			case 'on':
			  chrome.browserAction.setBadgeText({text:"\u25AA"});
			  chrome.browserAction.setBadgeBackgroundColor({color:[0,255,0,100]});
			  break;
			case '':
			  chrome.browserAction.setBadgeText({text:"\u00D7"});
			  chrome.browserAction.setBadgeBackgroundColor({color:[255,0,0,100]});
			  break;
			default:
			  chrome.browserAction.setBadgeText({text:""});
			}
		}	
	});
}

// Start on a specific window
function go(windowId) {
	if (localStorage["seconds"]) { timeDelay = (localStorage["seconds"]*1000);} // In milliseconds.
	moveinterval = setInterval(moveTabIfIdle, timeDelay);
        console.log('Starting: timeDelay:'+timeDelay+' | reload:'+tabReload+' | tabInactive: '+tabInactive+ ' | chromeFocusLost: '+chromeFocusLost);
	activeWindows.push(windowId);
	badgeTabs(windowId, 'on');
}

// Stop on a specific window
function stop(windowId) {
	clearInterval(moveinterval);
        console.log('Stopped.');
	var index = activeWindows.indexOf(windowId);
	if(index >= 0) {
		activeWindows.splice(index);
		badgeTabs(windowId, '');
	}
}

// Switch Tab URL functionality.
function activateTab(tab) {
	var windowId = tab.windowId
	chrome.tabs.update(tab.id, {'active': true});
	if (tabReload) {
		chrome.tabs.update(tab.id, {url: tab.url, selected: tab.selected}, null);
	}
}

// Call moveTab if the user isn't actually interacting with the browser
function moveTabIfIdle() {
	if ( tabInactive )
	{
		
		if(sessionIdleState || chromeFocusLost) {
			moveTab();
		} else {
			//Set "wait" color and log.
			chrome.browserAction.setBadgeText({text:"\u25AB"});
			chrome.browserAction.setBadgeBackgroundColor({color:[255,225,0,100]});
			//console.log('Browser was active, waiting.');
		}
		
	} else if ( chromeFocusTick )
	{
	
	} else {
		moveTab();
	}
}

// Switches to next tab in the active window.
function moveTab() {

	chrome.windows.getCurrent({populate:true}, function(wins){
		chrome.tabs.query({active:true}, function(tab) {
			var currentTab = tab[0].index;
			var nextTab = ( currentTab < wins.tabs.length-1) ? currentTab+1 : nextTab = 0;
			console.log(' -- Value of nextTab: ' +nextTab);
			activateTab(wins.tabs[nextTab]);
		});
	});	
	
	// MAY NEED THIS LATER!
	// chrome.tabs.query({'active': true}, function (tabs) {
		// var url = tabs[0].url;
		// console.log(' -- Current tab url: ' +url);
	// });
}